package com.woniuxy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.woniuxy.dao.MenuMapper;
import com.woniuxy.dao.RoleMapper;
import com.woniuxy.pojo.Menu;
import com.woniuxy.pojo.Role;
import com.woniuxy.service.RoleService;
import com.woniuxy.util.DataGridView;
import com.woniuxy.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService{
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Role> findAllRoles() {
        return roleMapper.selectAllRoles();
    }

    @Override
    public List<Role> selectRolesByUsid(int usid) {
        return this.roleMapper.selectRolesByUsid(usid);
    }

    @Override
    public DataGridView selectRolesByPage(RoleVo roleVo) {
        Page<Object> page = PageHelper.startPage(roleVo.getPage(), roleVo.getLimit());
        List<Role> roleList = roleMapper.selectAllRoles();
        return new DataGridView(page.getTotal(), roleList);
    }

    @Override
    public List<Menu> selectAllMenus() {
        return menuMapper.selectAllMenus();
    }

    @Override
    public String[] selectMenuIdsByRid(int rid) {
        List<Menu> menuList = this.menuMapper.selectMenusByRid(rid);
        String[] menuIds = new String[menuList.size()];
        for (int i = 0; i < menuList.size(); i++) {
            Menu menuItem = (Menu) menuList.get(i);
            menuIds[i] = menuItem.getId();
        }
        return menuIds;
    }

    @Transactional
    @Override
    public void assignRight(int rid, String[] mids) {
        this.roleMapper.deleteRoleMenuByRid(rid);
        if (mids != null && mids.length > 0) {
            for (String mid : mids) {
                this.roleMapper.insertRoleMenu(rid, mid);
            }
        }
    }

    @Override
    public void removeRoleById(int id) {
        this.roleMapper.deleteRoleMenuByRid(id);
        this.roleMapper.deleteRoleById(id);
    }
}
